package cn.edu.csust.cvs.management.service.impl;

import cn.edu.csust.cvs.management.common.ApiPageResult;
import cn.edu.csust.cvs.management.common.ApiResult;
import cn.edu.csust.cvs.management.controller.request.UserStatsPageQueryRequest;
import cn.edu.csust.cvs.management.controller.request.VideoStatsPageQueryRequest;
import cn.edu.csust.cvs.management.repository.ClipStatsViewRepository;
import cn.edu.csust.cvs.management.repository.UserStatsViewRepository;
import cn.edu.csust.cvs.management.repository.VideoStatsViewRepository;
import cn.edu.csust.cvs.management.repository.entity.ClipStatsView;
import cn.edu.csust.cvs.management.repository.entity.UserStatsView;
import cn.edu.csust.cvs.management.repository.entity.VideoStatsView;
import cn.edu.csust.cvs.management.service.StatsService;
import cn.edu.csust.cvs.management.service.domain.ClipStats;
import cn.edu.csust.cvs.management.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: snail
 * @Date: 2021/2/1 00:30
 * @Description: 审计管理服务实现
 */
@Service
public class StatsServiceImpl implements StatsService {

    @Autowired
    UserStatsViewRepository userStatsViewRepository;

    @Autowired
    VideoStatsViewRepository videoStatsViewRepository;

    @Autowired
    ClipStatsViewRepository clipStatsViewRepository;

    @Override
    public ApiPageResult<List<UserStatsView>> pageQuery(UserStatsPageQueryRequest request) {
        //规格定义
        Specification<UserStatsView> specification = new Specification<UserStatsView>() {
            /**
             * 构造断言
             * @param root 实体对象引用
             * @param query 规则查询对象
             * @param cb 规则构建对象
             * @return 断言
             */
            @Override
            public Predicate toPredicate(Root<UserStatsView> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if(StringUtils.isNotBlank(request.getName())){
                    Predicate likeName = cb.like(root.get("realname").as(String.class),"%"+request.getName()+"%");
                    predicates.add(likeName);
                }
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };
        //分页信息
        Sort sort;
        if (StringUtils.isNotBlank(request.getOrder())){
            sort = Sort.by(Sort.Direction.DESC,request.getOrder());
        }else{
            sort = Sort.by(Sort.Direction.DESC,"id");
        }
        Pageable pageable = PageRequest.of(request.getPageNo()-1,request.getPageSize(),sort);
        //查询
        Page<UserStatsView> page = this.userStatsViewRepository.findAll(specification,pageable);
        return ApiPageResult.ok(page.getTotalPages(),page.getTotalElements(),request.getPageSize(), (long) request.getPageNo(),page.getContent());
    }

    @Override
    public ApiPageResult<List<VideoStatsView>> pageQuery(VideoStatsPageQueryRequest request) {
        //规格定义
        Specification<VideoStatsView> specification = new Specification<VideoStatsView>() {

            /**
             * 构造断言
             * @param root 实体对象引用
             * @param query 规则查询对象
             * @param cb 规则构建对象
             * @return 断言
             */
            @Override
            public Predicate toPredicate(Root<VideoStatsView> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if(StringUtils.isNotBlank(request.getName())){
                    Predicate likeName = cb.like(root.get("videoName").as(String.class),"%"+request.getName()+"%");
                    predicates.add(likeName);
                }
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };
        //分页信息
        Sort sort;
        if (StringUtils.isNotBlank(request.getOrder())){
            sort = Sort.by(Sort.Direction.DESC,request.getOrder());
        }else{
            sort = Sort.by(Sort.Direction.DESC,"id");
        }
        Pageable pageable = PageRequest.of(request.getPageNo()-1,request.getPageSize(),sort);
        //查询
        Page<VideoStatsView> page = this.videoStatsViewRepository.findAll(specification,pageable);
        return ApiPageResult.ok(page.getTotalPages(),page.getTotalElements(),request.getPageSize(), (long) request.getPageNo(),page.getContent());
    }

    @Override
    public ApiResult<List<ClipStats>> statsVideoClip(Integer videoId) {

        List<ClipStatsView> views = clipStatsViewRepository.findByVideoId(videoId);
        if (CollectionUtils.isEmpty(views)){
            return ApiResult.ok(null);
        }
        List<ClipStats> stats = new ArrayList<>(20);
        views.stream().forEach(x->{
            ClipStats clipStats = new ClipStats();
            clipStats.setClipId(x.getClipId());
            clipStats.setStartTime(x.getStartTime());
            int startSeconds = DateUtils.convert(x.getStartTime());
            int endSeconds = startSeconds + x.getDuration();
            String endTime = DateUtils.format(endSeconds);
            clipStats.setEndTime(endTime);
            clipStats.setEditTimes(x.getEditTimes());
            stats.add(clipStats);
        });
        return ApiResult.ok(stats);
    }
}
